const sqlite3 = require('sqlite3');
const path = require('path');

//@Bean
class SpringSqlite3Jdbc {

	//@Value(value=YqSqlite3Orm.dbFile,force=false)
	dbFile='./data.db';

	//@Autowired
	springFactory;

	log;

	dataBase;

	async beanInit(){
		this.dataBase = await this.doConnect();
	}

	/**
	 * 链接
	 * 
	 * */
	doConnect(){

		const log = this.log.method('doConnect')

		const {dbFile} = this;
		const {rootPath} = this.springFactory.args;
		const dbPath = dbFile.indexOf(".") === 0 ? path.join(rootPath,dbFile) : dbFile;

		log.info(`连接数据库:${dbPath}`)
		
		return new Promise( (r,n) => {
			 const db = new sqlite3.Database(dbPath, (err) => {
		      if (err) {
		        n('Could not connect to database', err)
		      } else {
		        r(db)
		      }
		    })
		})
	}

	async run(sql,param=[]){
		this.log.method('run').trace({sql,param})
		return new Promise( (r,n) => {
			this.dataBase.run(sql,param, err => {
		        if (err) {
		            return n(err)
		        }
		        r(this)
		    })
		})
	}

	async all(sql,param=[]){
		this.log.method('all').trace({sql,param})
		return new Promise( (r,n) => {
			this.dataBase.all(sql,param,(err,rows) => {
		        if (err) {
		            return n(err)
		        }
		        r(rows)
		    })
		})
	}


	async close(){
		return new Promise( (r,n) => {
			this.dataBase.close((err,rows) => {
		        if (err) {
		            return n(err)
		        }
		        this.log.info(`close database success!`)
		        r()
		    })
		})
	}


}

module.exports = {SpringSqlite3Jdbc}